package com.chenyun.boot.web.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.chenyun.common.vo.AjaxResult;
import com.chenyun.satoken.starter.util.SaUtil;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 演示环境过滤器,演示环境不能修改数据
 * @author: lonni
 * @CreateTime: 2023-12-02  18:27
 * @Description:
 */
public class DemoOncePerRequestFilter extends OncePerRequestFilter {

    /**
     * 标识是否执行
     * @param request current HTTP request
     * @return false :总是执行 true 赛选,
     * @throws ServletException
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String method = request.getMethod();

       return !StrUtil.equalsAnyIgnoreCase(method,"PUT","POST","DELETE")||
               SaUtil.getLoginUser()==null;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        ServletUtil.write(response, JSONUtil.toJsonStr(AjaxResult.FAIL("演示模式,不允许修改数据!")),"application/json;charset=utf-8");
    }
}
